package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.exception.BizException;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.feign.CouponFeignService;
import com.atguigu.gulimail.product.feign.SearchFeignService;
import com.atguigu.gulimail.product.feign.WareFeignService;
import com.atguigu.gulimail.product.service.*;
import com.atguigu.gulimail.product.vo.*;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;

    @Resource
    SpuImagesService spuImagesService;

    @Resource
    AttrService attrService;

    @Resource
    ProductAttrValueService productAttrValueService;

    @Resource
    SkuInfoService skuInfoService;

    @Resource
    SkuImagesService skuImagesService;

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Resource
    BrandService brandService;

    @Resource
    CategoryService categoryService;

    @Resource
    WareFeignService wareFeignService;

    @Resource
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 商品添加，包含各种信息 -- spu，sku，基本属性，优惠券折扣，会员等级折扣。
     * TODO 对于失败情况的异常校验
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo vo) {

        // 1、保存商品基本信息 ‘pms_spu_info’
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        if (ObjectUtils.isNull(vo)) {
            throw new BizException(BizCodeEnum.VALID_EXCEPTION);
        }
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        // 2、保存spu的描述图片 pms_spu_info_desc
        // 将描述图片结果集按照相同的spuid 放在多列中显示，一列显示一个图片url
//        Long spuId = spuInfoEntity.getId();
//        List<String> decript = vo.getDecript();
//        if (!CollectionUtils.isEmpty(decript)){
//            decript.forEach(item -> {
//                SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
//                spuInfoDescEntity.setSpuId(spuId);
//                spuInfoDescEntity.setDecript(item);
//                spuInfoDescDao.insert(spuInfoDescEntity);
//            });
//        }
        // 将描述图片结果集，放在一列中显示，用逗号分割
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        // 3、保存spu的图片集  ’pms_spu_images’
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);
        // 4、保存spu的规格参数 --> 基本属性 ‘pms_sku_sale_attr_value’
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);
        // 5、保存spu的积分信息 --> 跨数据库gulimail_sms --> sms_spu_bounds 商品spu积分表
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        // 5、保存spu对应的所有sku信息 -->
        // 5.1)、保存sku的基本信息  ‘pms_sku_info’
        List<Skus> skus = vo.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {
            skus.forEach(item -> {
                // 找默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 5.2)、保存sku的图片信息  ‘pms_sku_images’
                // sku的自增主键ID
                Long skuId = skuInfoEntity.getSkuId();
                // 每保存一个sku基本信息，就同时保存一个图片！
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(img -> StringUtils.hasText(img.getImgUrl())).collect(Collectors.toList()); //没有图片路径的无需保存
                skuImagesService.saveBatch(imagesEntities);

                // 5.3)、保存sku的销售属性信息  ‘pms_sku_sale_attr_value’
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                // 5.4)、保存sku的优惠、满减等信息 --> 跨数据库gulimail_sms 优惠券库
                // 5.4.1)、 sms_sku_ladder 商品折扣表 --> 几件打几折
                // 5.4.2)、 sms_sku_full_reduction 商品满减表
                // 5.4.3)、 sms_member_price 会员价格表
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                // BigDecimal 比较 .compareTo --> 结果为-1代表<;为0=;为1>
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠折扣信息失败");
                    }
                }
            });
        }
    }

    /**
     * 可以根据品牌ID，三级分类ID，商品状态，以及检索KEY来进行模糊查询。
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String brandId = (String) params.get("brandId");
        if (ObjectUtils.isNotEmpty(brandId) && !Objects.equals(brandId, "0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (ObjectUtils.isNotEmpty(catelogId) && !Objects.equals(catelogId, "0")) {
            wrapper.eq("catalog_id", catelogId);
        }

        if (ObjectUtils.isNotEmpty(params.get("status"))) {
            wrapper.eq("publish_status", params.get("status"));
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("id", key).or()
                        .like("spu_description", key);
            });
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 商品上架 -- 存储到ES中
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 1、查出当前spuid对应的所有sku信息，包括 -- 品牌名...
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        // 收集当前sku集合中skuid的集合
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 查询当前sku能被检索规格属性,相同spu内的每个sku的规格属性都相同，只需在外面查一次即可。
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 查询出能够被检索的attr的id集合
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        // 把这个集合转换为set，方便下面判断
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        // 过滤出存在能被检索的attr集合,并且最终要收集成to中的attrs类型
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }).collect(Collectors.toList());
        // 发送远程调用，库存系统查询是否有库存
        // 并且为了防止因为网络波动原因，导致远程调用失败，如果失败就默认有库存。
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>() {};
            if (CollectionUtils.isNotEmpty(r.getData(typeReference))) {
                stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
            }
        } catch (Exception e) {
            log.error("库存服务查询有异常，原因{}",e);
        }
        // 2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            // 组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            // 把属性名一样的进行对拷，不一样的手动set
            BeanUtils.copyProperties(sku, esModel);
            // SkuPrice,SkuImg
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // hasStock,hotScore
            // 通过远程调用，库存系统查询是否有库存,设置库存信息
            esModel.setHasStock(!ObjectUtils.isNull(finalStockMap));
            // 热度评分。默认0
            esModel.setHotScore(0L);
            // 查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            // 设置检索属性
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());
        // 将数据发送给ES进行保存 -- gulimail-search-guoguo
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改当前spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            // 远程调用失败
            // TODO 重复调用 -- 接口幂等性 -- 重试机制。
            // Feign的调用流程
            /**
             * 1、构造请求数据，将数据转为Json
             * 构造请求模板-- RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2、发送请求进行执行 -- 执行成功会解码响应数据：executeAndDecode(template);
             * 3、执行请求会有重试机制
             *      while(true){
             *          try{
             *              executeAndDecode(template);
             *          }catch(){
             *              try{retryer.continueOrPropagate(e);}catch(){throw ex;}
             *              continue;
             *          }
             *      }
             */
        }
    }


    /**
     * by leiShen
     */
//    @Override
//    public PageUtils queryPageByCondition(Map<String, Object> params) {
//
//        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
//
//        String key = (String) params.get("key");
//        if(!StringUtils.isEmpty(key)){
//            wrapper.and((w)->{
//                w.eq("id",key).or().like("spu_name",key);
//            });
//        }
//        // status=1 and (id=1 or spu_name like xxx)
//        String status = (String) params.get("status");
//        if(!StringUtils.isEmpty(status)){
//            wrapper.eq("publish_status",status);
//        }
//
//        String brandId = (String) params.get("brandId");
//        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
//            wrapper.eq("brand_id",brandId);
//        }
//
//        String catelogId = (String) params.get("catelogId");
//        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
//            wrapper.eq("catalog_id",catelogId);
//        }
//
//        /**
//         * status: 2
//         * key:
//         * brandId: 9
//         * catelogId: 225
//         */
//
//        IPage<SpuInfoEntity> page = this.page(
//                new Query<SpuInfoEntity>().getPage(params),
//                wrapper
//        );
//
//        return new PageUtils(page);
//    }


}